#!/usr/bin/perl -w

###############################################################################
# Load the processed idlink file into the idlink table in the database
#
# Parameters needed: dbname, username, temp_dir
# Assumptions: $TEMP_DIR/idlink.out exists
#
# Author: Herodotos Herodotou and Nedyalko Borisov
# Date: March 11, 2010
#
##############################################################################

use getOpts qw(get_options println);

if ($#ARGV != 0)
{
   println qq(Please specify the .properties file);
   println qq(Usage: perl $0 load.properties);
   exit(-1);
}

# Get input parameters
%opt = get_options($ARGV[0]);
$DB_NAME  =$opt{'dbname'};
$USERNAME =$opt{'username'};
$TEMP_DIR = $opt{'temp_dir'};

println qq(Loading idlink data);

# Load the data
$load_script = qq($TEMP_DIR/load_idlink.sql);
open  OUTFILE, ">", $load_script or die $!;
print OUTFILE qq(BEGIN TRANSACTION;\n);
print OUTFILE qq(SET CONSTRAINTS ALL DEFERRED;\n);
print OUTFILE qq(\\COPY idlink(exp_id, patient_id, study_id, sample_id)).
              qq( FROM '$TEMP_DIR/idlink.out' WITH DELIMITER AS ','\n);
print OUTFILE qq(COMMIT;\n);
close OUTFILE;

!system qq(psql -U $USERNAME -d $DB_NAME -f $load_script > /dev/null) or die $!;
!system qq(psql -U $USERNAME -d $DB_NAME -c "ANALYZE idlink" > /dev/null) or die $!;
!system qq(rm -f $load_script) or die $!;

# Remove the out file
!system qq(rm -f $TEMP_DIR/idlink.out) or die $!;

println qq(Completed loading idlink data);

